package com.itheima.health.util;

import com.alibaba.druid.util.StringUtils;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferUtils;
import org.springframework.http.server.reactive.ServerHttpRequest;
import reactor.core.publisher.Flux;

import java.nio.CharBuffer;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Consumer;

public class RequestUtils {
    public static Map<String, String> getFormMap(ServerHttpRequest serverHttpRequest) {
        Flux<DataBuffer> body = serverHttpRequest.getBody();
        AtomicReference<String> bodyRef = new AtomicReference<>();
        Consumer<? super DataBuffer> c = (b -> {
            CharBuffer charBuffer = StandardCharsets.UTF_8.decode(b.asByteBuffer());
            DataBufferUtils.release(b);
            bodyRef.set(charBuffer.toString());
        });
        body.subscribe(c);

        String rspStr = bodyRef.get();
        if (StringUtils.isEmpty(rspStr)) {
            return null;
        }
        return getFormMap(rspStr);
    }

    private static Map<String, String> getFormMap(String body) {
        if (StringUtils.isEmpty(body)) {
            return null;
        }
        Map<String, String> map = new HashMap<>();
        String[] params = body.split("&");  // name=123&age=11 ==>  ['name=123','age=11']
        for (String param : params) {
            String[] par = param.split("="); // name=123 ==>  ['name','123']
            if (par != null && par.length > 1) {
                map.put(par[0], par[1]);
            }
        }
        return map;
    }
}
